package com.jrzh.mvc.controller.sys.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jrzh.common.cache.CacheManager;
import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.utils.IpUtil;
import com.jrzh.common.utils.PasswordUtils;
import com.jrzh.config.ProjectConfigration;
import com.jrzh.framework.I18nHelper;
import com.jrzh.framework.annotation.NoAdminLogin;
import com.jrzh.framework.annotation.NoPermission;
import com.jrzh.framework.annotation.UserEvent;
import com.jrzh.framework.base.controller.BaseAdminController;
import com.jrzh.framework.bean.ResultBean;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.framework.contants.GeneralConstant;
import com.jrzh.mvc.constants.CacheConstants;
import com.jrzh.mvc.constants.SysConstant;
import com.jrzh.mvc.constants.SysConstant.LOGIN_STATUS;
import com.jrzh.mvc.convert.sys.UserConvert;
import com.jrzh.mvc.model.sys.LoginLogModel;
import com.jrzh.mvc.model.sys.UserModel;
import com.jrzh.mvc.service.sys.manage.SysServiceManage;
import com.jrzh.mvc.view.sys.LoginFormView;
import com.jrzh.mvc.view.sys.UserView;

@RestController(IndexController.LOCATION +"/IndexController")
@RequestMapping(IndexController.LOCATION)
public class IndexController extends BaseAdminController{
	
	public static final String LOCATION = "sys/admin/layout";
	
	@Autowired
	SysServiceManage sysServiceManage;
	
	@Autowired
	ProjectConfigration projectConfigration;
	
	SessionUser sessionUser = new SessionUser();
	
	@PostMapping(value = "login")
	@UserEvent(desc = "管理员登陆")
	@NoAdminLogin
	@NoPermission
	public ResultBean doLogin(@Valid @ModelAttribute("LoginFormView") LoginFormView loginFormBean, BindingResult errors, HttpServletRequest request, HttpSession session){
		
		ResultBean result = new ResultBean();
		try {
			String message = "";
			String status = "";
			if (errors.hasErrors()) {
				message = errors.getFieldError().getDefaultMessage();
				result.setMsg(message);
				result.setStatus(LOGIN_STATUS.ERROR);
				return result;
			}
			String sessionValidateCode = (String)session.getAttribute(GeneralConstant.SESSION_KEY.VERIFY_CODE);
			Boolean isEnable = projectConfigration.adminLoginValidateCodeEnable;
			Boolean vc_result = true;
			if(isEnable){
				vc_result = StringUtils.equalsIgnoreCase(sessionValidateCode, loginFormBean.getValidateCode());
			}
			if(!vc_result){
				result.setMsg(I18nHelper.getI18nByKey("message.verification_error", sessionUser));
				result.setStatus(LOGIN_STATUS.VERIFICATION_CODE_ERROR);
				return result;
			}
			String loginName = loginFormBean.getLoginName();
			String loginPass = loginFormBean.getLoginPass();
			SessionUser sessionUser = sysServiceManage.loginService.login(loginName, loginPass, "");
			String uuid = UUID.randomUUID().toString();
			sessionUser.setUuid(uuid);
			CacheManager.putCacheInfo(uuid, sessionUser, CacheConstants.LOGIN_TIME_OUT);
			LoginLogModel loginLog= new LoginLogModel();
			UserModel user =  sysServiceManage.userService.findByField("code", loginFormBean.getLoginName());
	        Boolean isOpen = sysServiceManage.manegeInfoService.checkStatus(getSessionUser(),user);
	        if (!isOpen) {
	                result.setMsg("系统权限校验失败,权限检验错误");
	                return result;
	        }
	        if(null !=user ){
	        	loginLog.setUserId(user.getId());
	        	loginLog.setLoginTime(new Date());
	        	loginLog.setLoginOutTime(null);
	        	String mac=IpUtil.getMACAddress();
	        	if(StringUtils.isNotBlank(mac)){
	        		loginLog.setDescription("["+user.getName()+"]"+ I18nHelper.getI18nByKey("message.admin_login", sessionUser) +","+ I18nHelper.getI18nByKey("message.mac_address", sessionUser) +":"+mac);
	        		loginLog.setMacAddress(mac);
	        	}else{
	        		loginLog.setDescription("["+user.getName()+"]" + I18nHelper.getI18nByKey("message.admin_login", sessionUser));
	        	}
	        	loginLog.setIp(IpUtil.getIpAddr(request));
        		loginLog.setType(SysConstant.LOGIN_TYPE.LOGIN);
				sysServiceManage.loginLogService.add(loginLog , SessionUser.getSystemUser());
				result.setStatus(ResultBean.SUCCESS);
				result.setMsg(I18nHelper.getI18nByKey("message.landed_successfully", sessionUser));
				result.setObjs(new Object[]{sessionUser});
	        }else{
	        	result.setMsg("用户未登录");
			}
		}catch (Exception e) {// 帐号被锁定
			e.printStackTrace();
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	@PostMapping(value = "loginout")
	@UserEvent(desc = "管理员注销")
	@NoPermission
	public ResultBean doLoginout(HttpServletResponse response) {
		ResultBean result = new ResultBean();
		try {
			SessionUser user = getSessionUser();
			try {
				LoginLogModel loginLog= new LoginLogModel();
				loginLog.setUserId(user.getId());
				loginLog.setLoginTime(null);
				loginLog.setLoginOutTime(new Date());
				String mac=IpUtil.getMACAddress();
				loginLog.setDescription("["+user.getName()+"]"+ I18nHelper.getI18nByKey("message.admin_sign_out", getSessionUser()) +","+ I18nHelper.getI18nByKey("message.mac_address", getSessionUser()) +":"+mac);
				loginLog.setMacAddress(mac);
				loginLog.setIp(IpUtil.getIpAddr(request));
				loginLog.setType(SysConstant.LOGIN_TYPE.LOGIN_OUT);
				sysServiceManage.loginLogService.add(loginLog , SessionUser.getSystemUser());
			} catch (Exception e) {
				throw new ProjectException(e.getMessage());
			}
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("cache-control", "no-store");
			CacheManager.clearOnly(user.getUuid());
			result.setStatus(ResultBean.SUCCESS);
		} catch (ProjectException e) {
			e.printStackTrace();
			result.setMsg(e.getMessage());
			result.setStatus(ResultBean.ERROR);
		}
		return result;
	}
	
	@PostMapping(value = "changepassword")
	public ResultBean doChangepassword(){
		ResultBean result = new ResultBean();
		String message = "";
		try {
			String oldPassword = request.getParameter("oldPassword");
			String newPassword = request.getParameter("newPassword");
			String repeatPassword = request.getParameter("repeatPassword");
			UserModel user = sysServiceManage.userService.findById(getSessionUser().getId());
		    String realPass = PasswordUtils.encryptPassword(oldPassword,user.getSalt());
			 if(StringUtils.equals(user.getPassword(), realPass)){
			   if(StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(repeatPassword)){
				 if(StringUtils.equals(newPassword, repeatPassword)){
							user.setPassword(PasswordUtils.encryptPassword(newPassword,user.getSalt()));
							sysServiceManage.userService.edit(user, getSessionUser());
							result.setMsg(I18nHelper.getI18nByKey("message.change_password", getSessionUser()));
							result.setStatus(ResultBean.SUCCESS);
							return result;
						}else{
							message = I18nHelper.getI18nByKey("message.pwd_inconsistent", getSessionUser());
						}
					}else{
						message = I18nHelper.getI18nByKey("message.pwd_invalid", getSessionUser());
					}
				}else{
					message = I18nHelper.getI18nByKey("message.old_pwd_incorrect", getSessionUser());
				}
		} catch (Exception e) {
			e.printStackTrace();
			message = e.getMessage();
			if(StringUtils.isBlank(message)){
				try {
					message = I18nHelper.getI18nByKey("message.system_exception", getSessionUser());
				} catch (ProjectException e1) {
					e1.printStackTrace();
				}
			}
		}
		result.setMsg(message);
		return result;
	}
	
	@PostMapping(value = "changeAuditPassword")
	public ResultBean doChangeAuditPassword(){
		ResultBean result = new ResultBean();
		String message = "";
		try {
			String oldPassword = request.getParameter("oldPassword");
			String newPassword = request.getParameter("newPassword");
			String repeatPassword = request.getParameter("repeatPassword");
			UserModel user = sysServiceManage.userService.findById(getSessionUser().getId());
		    String realPass = PasswordUtils.encryptPassword(oldPassword,user.getSalt());
			 if(StringUtils.equals(user.getAuditPassword(), realPass)){
			   if(StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(repeatPassword)){
				 if(StringUtils.equals(newPassword, repeatPassword)){
							user.setAuditPassword(PasswordUtils.encryptPassword(newPassword,user.getSalt()));
							sysServiceManage.userService.edit(user, getSessionUser());
							result.setMsg(I18nHelper.getI18nByKey("message.edit_pwd_success", getSessionUser()));
							result.setStatus(ResultBean.SUCCESS);
							return result;
						}else{
							message = I18nHelper.getI18nByKey("message.pwd_inconsistent", getSessionUser());
						}
					}else{
						message = I18nHelper.getI18nByKey("message.pwd_invalid", getSessionUser());
					}
				}else{
					message = I18nHelper.getI18nByKey("message.old_pwd_incorrect", getSessionUser());
				}
		} catch (Exception e) {
			e.printStackTrace();
			message = e.getMessage();
			if(StringUtils.isBlank(message)){
				try {
					message = I18nHelper.getI18nByKey("message.system_exception", getSessionUser());
				} catch (ProjectException e1) {
					e1.printStackTrace();
				}
			}
		}
		result.setMsg(message);
		return result;
	}
	
	@PostMapping(value = "changePersonalInfo")
	@UserEvent(desc = "管理员修改")
	public ResultBean changePersonalInfo(UserView view) {
		ResultBean result = new ResultBean();
		try {
			if(StringUtils.isBlank(view.getCode())){
				result.setMsg(I18nHelper.getI18nByKey("message.account_not_found_null", getSessionUser()));
				return result;
			}
			if(StringUtils.isBlank(view.getName())){
				result.setMsg(I18nHelper.getI18nByKey("message.name_not_found", getSessionUser()));
				return result;
			}
			if(StringUtils.isNotBlank(view.getRemark())){
				if(view.getRemark().length() > 512){
					result.setMsg(I18nHelper.getI18nByKey("message.remarks_too_long", getSessionUser()));
					return result;
				}
			}
		} catch (ProjectException e) {
			e.printStackTrace();
		}
/*		if(StringUtils.isNotBlank(view.getAddress())){
			if(view.getRemark().length() > 256){
				result.setMsg("地址篇幅过长，请不要超过50个字");
				return result;
			}
		}*/
		try {
			UserModel model = sysServiceManage.userService.findById(getSessionUser().getId());
			model = new UserConvert().editConvert(view, model);
			log.info(view);
			log.info(model);
			sysServiceManage.userService.edit(model, getSessionUser());
			result.setStatus(ResultBean.SUCCESS);
			result.setMsg(I18nHelper.getI18nByKey("message.modify_success", sessionUser));
		}catch (Exception ex) {
			ex.printStackTrace();
			result.setMsg(ex.getMessage());
		}
		return result;
	}
	
	
	@PostMapping(value = "getModules")
	@NoAdminLogin
	public ResultBean getModules(){
		ResultBean result = new ResultBean();
		try {
			result.setStatus(ResultBean.SUCCESS);
			result.setObjs(new Object[]{SysConstant.MODULE_LIST});
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return result;
	}
	
	@PostMapping(value = "saveLang/{lang}")
	@NoPermission
	public ResultBean saveLang(@PathVariable("lang") String lang){
		ResultBean result = new ResultBean();
		try { 
			SessionUser sessionUser = getSessionUser();
			sysServiceManage.userSettingService.saveLang(lang, sessionUser);
			result.setStatus(ResultBean.SUCCESS);
			result.setObjs(sessionUser);
		} catch (Exception e) {
			log.error(e.getMessage());
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	@Override
	protected void setData() {
		Map<String, Object> attrs = new HashMap<String, Object>();
		if(getSessionUser()==null){
			sessionUser.setAttrs(attrs);
			attrs.put("lang", "hk");
		}
	}
	
	@PostMapping(value = "getEndTime/{id}")
	@NoPermission
	public ResultBean getEndTime(@PathVariable("id") String id) {
		ResultBean result = new ResultBean();
		try {
			result = new ResultBean();
			result.setObjs(new Object[] { sysServiceManage.userService.findViewById(id) });
			result.setStatus(ResultBean.SUCCESS);
			result.setMsg("查询成功");
		} catch (Exception e) {
			log.error(e.getMessage());
			result.setMsg(e.getMessage());
		}
		return result;
	}
}
